package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrderDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 前台历史订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        Page<OrderDto> orderDtoPage = orderService.queryOrderPage(page, pageSize);
        return R.success(orderDtoPage);
    }

    /**
     * 后台订单明细分页查询
     * 根据订单号，时间段查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime) {
        //获取userId
        Long userId = BaseContext.getCurrentId();
        //分页构造器
        Page pageInfo = new Page(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //按订单号查询
        queryWrapper.like(number != null, Orders::getNumber, number);
        //按时间段查询,大于开始，小于结束
        queryWrapper.gt(!StringUtils.isEmpty(beginTime), Orders::getOrderTime, beginTime)
                .lt(!StringUtils.isEmpty(endTime), Orders::getOrderTime, endTime);
        //按时间降序排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //执行查询
        Page result = orderService.page(pageInfo, queryWrapper);
        if (result == null) {
            return R.error("查询失败！");
        }
        return R.success(pageInfo);
    }

    /**
     * 后台更改订单的派送状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<Orders> update(@RequestBody Orders orders) {
        log.info("orders对象的数据：{}", orders);
        //获取前端传过来订单的状态和id
        Integer status = orders.getStatus();
        Long ordersId = orders.getId();
        //设置构造器，根据orderid查询出order对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, ordersId);
        Orders orderServiceOne = orderService.getOne(queryWrapper);
        //更新订单的状态
        orderServiceOne.setStatus(status);
        boolean result = orderService.updateById(orderServiceOne);
        if (!result) {
            return R.error("订单状态更新失败");
        }
        return R.success(orderServiceOne);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders order) {
        //这里的参数只有orderId一个
//        log.info("order:{}", order);
        //获取orderId
        Long orderId = order.getId();
        //条件构造器
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        //查询订单的口味细节数据
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> details = orderDetailService.list(queryWrapper);
        //获取用户id，待会需要set进去
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = details.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //拷贝属性
            BeanUtils.copyProperties(item, shoppingCart);
            //set用户id回去
            shoppingCart.setUserId(userId);
            //set创建时间回去
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将上次所支付的订单菜品重新加入到购物车
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("喜欢吃可以再来一单！");
    }

}
